package com.vick.com;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gen.tool.AlertDialog_PG;
import com.gen.tool.SoundPlayer;
import com.ouken.com.R;
import com.ouken.tool.ConnectServer;
import com.ouken.tool.MyApp;
import com.vick.task.GetImageTask;
import com.vick.tool.DialogTool;
import com.vick.tool.MiscTool;

public class ChallengerplayingActivity extends Activity { // role=provider,challenger
	KeyButton key[];
	ImageButton ib_quit;
	TextView tv_time,tv_leftcount;
	ImageView iv_provider_img, iv_player_img[];
	TextView tv_provider_name, tv_player_name[];
	TextView tv_player_pt[];
	ImageView iv_player_pane[];
	ImageView iv_hangman, iv_picture;
	boolean isProvider;
	//private MplayerTool mplayerTool;
	private CountDownTimer countDown = new CountDownTimer(20000, 1000) {
		public void onTick(long millisUntilFinished) {
			tv_time.setText(Long.toString(millisUntilFinished / 1000));
		}

		public void onFinish() {
			new SendLetterTask().execute("pass");
		}

	};
	private Handler mHandler = new Handler();
	int[] ib_key_id = { R.id.challengerplayingActivity_ib_a,
			R.id.challengerplayingActivity_ib_b,
			R.id.challengerplayingActivity_ib_c,
			R.id.challengerplayingActivity_ib_d,
			R.id.challengerplayingActivity_ib_e,
			R.id.challengerplayingActivity_ib_f,
			R.id.challengerplayingActivity_ib_g,
			R.id.challengerplayingActivity_ib_h,
			R.id.challengerplayingActivity_ib_i,
			R.id.challengerplayingActivity_ib_j,
			R.id.challengerplayingActivity_ib_k,
			R.id.challengerplayingActivity_ib_l,
			R.id.challengerplayingActivity_ib_m,
			R.id.challengerplayingActivity_ib_n,
			R.id.challengerplayingActivity_ib_o,
			R.id.challengerplayingActivity_ib_p,
			R.id.challengerplayingActivity_ib_q,
			R.id.challengerplayingActivity_ib_r,
			R.id.challengerplayingActivity_ib_s,
			R.id.challengerplayingActivity_ib_t,
			R.id.challengerplayingActivity_ib_u,
			R.id.challengerplayingActivity_ib_v,
			R.id.challengerplayingActivity_ib_w,
			R.id.challengerplayingActivity_ib_x,
			R.id.challengerplayingActivity_ib_y,
			R.id.challengerplayingActivity_ib_z };
	int[] key_img_id = { R.drawable.key_a, R.drawable.key_b, R.drawable.key_c,
			R.drawable.key_d, R.drawable.key_e, R.drawable.key_f,
			R.drawable.key_g, R.drawable.key_h, R.drawable.key_i,
			R.drawable.key_j, R.drawable.key_k, R.drawable.key_l,
			R.drawable.key_m, R.drawable.key_n, R.drawable.key_o,
			R.drawable.key_p, R.drawable.key_q, R.drawable.key_r,
			R.drawable.key_s, R.drawable.key_t, R.drawable.key_u,
			R.drawable.key_v, R.drawable.key_w, R.drawable.key_x,
			R.drawable.key_y, R.drawable.key_z };
	int[] key2_img_id = { R.drawable.key2_a, R.drawable.key2_b,
			R.drawable.key2_c, R.drawable.key2_d, R.drawable.key2_e,
			R.drawable.key2_f, R.drawable.key2_g, R.drawable.key2_h,
			R.drawable.key2_i, R.drawable.key2_j, R.drawable.key2_k,
			R.drawable.key2_l, R.drawable.key2_m, R.drawable.key2_n,
			R.drawable.key2_o, R.drawable.key2_p, R.drawable.key2_q,
			R.drawable.key2_r, R.drawable.key2_s, R.drawable.key2_t,
			R.drawable.key2_u, R.drawable.key2_v, R.drawable.key2_w,
			R.drawable.key2_x, R.drawable.key2_y, R.drawable.key2_z };
	int[] iv_hangman_id = { R.drawable.hang1, R.drawable.hang2,
			R.drawable.hang3, R.drawable.hang4, R.drawable.hang5,
			R.drawable.hang6, R.drawable.hang7, R.drawable.hang8,
			R.drawable.hang9, R.drawable.hang10 };
	int[] tv_pname_id = { R.id.challengerplayingActivity_tv_p1name,
			R.id.challengerplayingActivity_tv_p2name,
			R.id.challengerplayingActivity_tv_p3name,
			R.id.challengerplayingActivity_tv_p4name };
	int[] tv_pscore_id = { R.id.challengerplayingActivity_tv_p1pt,
			R.id.challengerplayingActivity_tv_p2pt,
			R.id.challengerplayingActivity_tv_p3pt,
			R.id.challengerplayingActivity_tv_p4pt };
	int[] iv_ppane_id = { R.id.challengerplayingActivity_iv_player1pane,
			R.id.challengerplayingActivity_iv_player2pane,
			R.id.challengerplayingActivity_iv_player3pane,
			R.id.challengerplayingActivity_iv_player4pane };
	int[] iv_pimg_id = { R.id.challengerplayingActivity_iv_p1img,
			R.id.challengerplayingActivity_iv_p2img,
			R.id.challengerplayingActivity_iv_p3img,
			R.id.challengerplayingActivity_iv_p4img };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Bitmap bmp =
		// BitmapFactory.decodeResource(getResources(),R.drawable.crown);
		// System.out.println("next is bitmap ja");
		// System.out.println(BitmapTool.bitMapToString(bmp));

		setContentView(R.layout.challengerplaying);
		//mplayerTool = new MplayerTool(ChallengerplayingActivity.this);
		/*----- Set isProvider -----*/
		Intent intent = getIntent();
		String role = intent.getStringExtra("role");
		if ("provider".equals(role)) {
			isProvider = true;
		} else {
			isProvider = false;
		}
		/*----- Set View -----*/
		ib_quit = (ImageButton) findViewById(R.id.challengerplayingActivity_ib_quit);
		tv_time = (TextView) findViewById(R.id.challengerplayingActivity_tv_time);
		iv_hangman = (ImageView) findViewById(R.id.challengerplayingActivity_iv_hangman);
		iv_provider_img = (ImageView) findViewById(R.id.challengerplayingActivity_iv_providerimg);
		tv_provider_name = (TextView) findViewById(R.id.challengerplayingActivity_tv_providername);
		iv_picture = (ImageView) findViewById(R.id.challengerplayingActivity_iv_picture);
		tv_leftcount=(TextView) findViewById(R.id.challengerplaying_tv_leftcount);
		
		tv_player_name = new TextView[4];
		tv_player_pt = new TextView[4];
		iv_player_pane = new ImageView[4];
		iv_player_img = new ImageView[4];
		for (int i = 0; i < 4; i++) {
			tv_player_name[i] = (TextView) findViewById(tv_pname_id[i]);
			tv_player_pt[i] = (TextView) findViewById(tv_pscore_id[i]);
			iv_player_pane[i] = (ImageView) findViewById(iv_ppane_id[i]);
			iv_player_img[i] = (ImageView) findViewById(iv_pimg_id[i]);
		}
		key = new KeyButton[26];
		for (int i = 0; i < 26; ++i) {
			char c = (char) (97 + i);
			key[i] = new KeyButton((ImageButton) findViewById(ib_key_id[i]), c);

		}
		// if (!isProvider) {
		// setClickAll();
		// }
		ib_quit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				new QuitGameTask().execute();

			}
		});

		/*----- Update game task -----*/

		mHandler.removeCallbacks(updateGameTask);
		mHandler.post(updateGameTask);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(updateGameTask);
		countDown.cancel();
	}
	/*gen added for music*/
	@Override
	protected void onResume() {
		super.onResume();
		SoundPlayer.playSound(R.raw.startgame_entergameroom);
	}

	private String oldMissedChars = "";
	private String oldCorrected = "";

	private void updateKeyHangman(String corrected, String missedChars) {
		missedChars = missedChars.toUpperCase();
		if (oldMissedChars.equals(missedChars)
				&& oldCorrected.equals(corrected)) // if no update, don't do
													// anything
			return;

		oldMissedChars = missedChars;
		oldCorrected = corrected;

		for (int i = 0; i < 26; i++) {
			if (missedChars.indexOf(key[i].alphabet) == -1
					&& corrected.indexOf(key[i].alphabet) == -1) {// not in
																	// missedChars
																	// and
																	// corrected
				key[i].setIbValid();
			} else {// in missedChars or corrected
				key[i].setIbInvalid();
			}
		}
		if (missedChars.length() == 0) {
			iv_hangman.setImageResource(android.R.color.transparent);
		} else {
			iv_hangman
					.setImageResource(iv_hangman_id[missedChars.length() - 1]);
		}
		tv_leftcount.setText((10-missedChars.length())+" left");
	}

	private String oldWord = "";

	private void updateWord(String word) {// A**LE
		if (oldWord.equals(word)) // if no update, don't do anything
			return;

		oldWord = word;

		int len = word.length();
		LinearLayout lo_word = (LinearLayout) findViewById(R.id.challengerplayingActivity_layout_word);
		lo_word.removeAllViews();
		word = word.toUpperCase();
		for (int i = 0; i < len; ++i) {
			LinearLayout v = (LinearLayout) LayoutInflater.from(this).inflate(
					R.layout.challengerplaying_aletter, null);
			TextView tv_alphabet = (TextView) v.getChildAt(0);
			char c = word.charAt(i);
			if (c < 'A' || c > 'Z') {
				tv_alphabet.setText(" ");
			} else {
				tv_alphabet.setText(Character.toString(c));
			}
			lo_word.addView(v);
		}
	}

	private String challengerImageURL[] = new String[4];

	private void updateChallenger(Player[] players) {
		int i;

		MyApp myApp = (MyApp) getApplicationContext();
		String myMail = myApp.getUserEmail();

		for (i = 0; i < players.length; ++i) {
			if (players[i].email.equals(myMail)) {
				tv_player_name[i].setText(players[i].name + "(me)");
			} else {
				tv_player_name[i].setText(players[i].name);
			}

			tv_player_pt[i].setText(Integer.toString(players[i].score) + " pt");

			if (players[i].imageURL.equals(challengerImageURL[i]))
				return;
			new GetImageTask(iv_player_img[i]).execute(players[i].imageURL);

			if (players[i].isHisTurn) {
				iv_player_pane[i].setImageResource(R.drawable.panel_yellow);
			} else {
				iv_player_pane[i].setImageResource(R.drawable.panel_white);
			}
		}
		for (; i < 4; ++i) {
			tv_player_name[i].setText("");
			tv_player_pt[i].setText("");
			iv_player_img[i].setImageResource(R.drawable.people_small);
			iv_player_pane[i].setImageResource(R.drawable.panel_white);
		}
	}

	private String oldProviderImageURL;

	private void setProvider(Player player) {
		MyApp myApp = (MyApp) getApplicationContext();
		String myMail = myApp.getUserEmail();
		if ("none".equals(player.email)) {
			tv_provider_name.setText("");
			iv_provider_img.setImageBitmap(null);
		} else {
			if (player.email.equals(myMail)) {
				tv_provider_name.setText(player.name + "(me)");
			} else {
				tv_provider_name.setText(player.name);
			}

			if (player.imageURL.equals(oldProviderImageURL))
				return;
			oldProviderImageURL = player.imageURL;
			new GetImageTask(iv_provider_img).execute(player.imageURL);
		}
	}

	private String oldQuestionImageStr;

	private void setQuestionImage(String imageStr) {
		if (imageStr.equals(oldQuestionImageStr))
			return;

		new GetImageTask(iv_picture).execute("question/" + imageStr);
		oldQuestionImageStr = imageStr;
	}

	private void setClickAll() {
		for (int i = 0; i < this.key.length; i++) {
			this.key[i].setClick();
		}
	}

	private void removeClickAll() {
		for (int i = 0; i < this.key.length; i++) {
			this.key[i].removeClick();
		}
	}

	private boolean isMyTurn;

	private void startMyTurn() {
		if (isMyTurn)
			return;
		isMyTurn = true;
		//gen added
		SoundPlayer.playSound(R.raw.myturn_chanllengerplaying);
		DialogTool
				.showFlashMessage(ChallengerplayingActivity.this, "Your Turn");
		setClickAll();
		countDown.start();
	}

	private void endMyTurn() {
		if (!isMyTurn)
			return;
		isMyTurn = false;
		removeClickAll();
		countDown.cancel();
		tv_time.setText("--");
	}

	private class KeyButton {
		char alphabet;
		int state;// 1 valid 0 invalid
		ImageButton ib;

		KeyButton(ImageButton i, char a) {
			ib = i;
			alphabet = Character.toUpperCase(a);
			state = 1;
		}

		void setIbValid() {
			if (state == 1)
				return;
			state = 1;
			ib.setImageResource(key_img_id[(int) alphabet - 65]);
			setClick();
		}

		void setIbInvalid() {
			if (state == 0)
				return;
			state = 0;
			ib.setImageResource(key2_img_id[(int) alphabet - 65]);
			removeClick();
		}

		void setClick() {
			if (state != 1)
				return;
			ib.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					SoundPlayer.playSound(R.raw.keypress_common);
					//mplayerTool
							//.playButtonPressed(ChallengerplayingActivity.this);
					setIbInvalid();
					new SendLetterTask().execute(Character.toString(alphabet));
				}
			});
		}

		void removeClick() {
			ib.setOnClickListener(null);
		}
	}

	private class SendLetterTask extends AsyncTask<String, Void, String> {
		private AlertDialog_PG progressDialog;

		@Override
		protected void onPreExecute() {
			endMyTurn();
			progressDialog = DialogTool.showProgressDialog(ChallengerplayingActivity.this, "Sending answer");
		}

		@Override
		protected String doInBackground(String... params) {// params = alphabet
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			connectParams.add(new BasicNameValuePair("email", myApp
					.getUserEmail()));
			connectParams.add(new BasicNameValuePair("roomname", myApp
					.getRoomName()));
			connectParams.add(new BasicNameValuePair("MAC", myApp.getMac()));
			connectParams.add(new BasicNameValuePair("answer", params[0]));
			connectParams.add(new BasicNameValuePair("ParamEnd",
					"ParamEndParamEndParamEnd"));
			return ConnectServer.connect(
					"http://" + ConnectServer.getServerAdd()
							+ "/challenger/answer-game", connectParams);
		}

		@Override
		protected void onPostExecute(String result) {
			DialogTool.cancelProgressDialog(progressDialog);
			if (!DialogTool.checkNetworkAlive(result,
					ChallengerplayingActivity.this, null))
				return;
			if(!DialogTool.checkLogin(result, ChallengerplayingActivity.this))
				return;

			String[] resultParam = result.split(",");

			if ("OK".equals(resultParam[0])) {
				if (resultParam[2].contains("*")
						&& (resultParam.length < 4 || (resultParam.length >= 4 && resultParam[3]
								.length() < 10))) {

					if ("T".equals(resultParam[1])) {
						//gen added
						SoundPlayer.playSound(R.raw.correct_chanllengerplaying);
						DialogTool.showFlashMessage(
								ChallengerplayingActivity.this,
								"Correct \\(^ w ^)/");
					} else if ("F".equals(resultParam[1])) {
						SoundPlayer.playSound(R.raw.incorrect_challengerplaying);
						DialogTool.showFlashMessage(
								ChallengerplayingActivity.this,
								"Wrong ( T o T )");
					} else {
						DialogTool.showFlashMessage(
								ChallengerplayingActivity.this, "Pass");
					}
				}
				updateWord(resultParam[2]);
				if (resultParam.length < 4)
					updateKeyHangman(resultParam[2], "");
				else
					updateKeyHangman(resultParam[2], resultParam[3]);
			} else {
				DialogTool.showCustomMessage(ChallengerplayingActivity.this, result);
			}
		}
	}

	private class QuitGameTask extends AsyncTask<String, Void, String> {
		private AlertDialog_PG progressDialog;

		@Override
		protected void onPreExecute() {
			countDown.cancel();
			mHandler.removeCallbacks(updateGameTask);
			progressDialog = DialogTool.showProgressDialog(ChallengerplayingActivity.this, "Quitting...");
		}

		@Override
		protected String doInBackground(String... params) {
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			if (isProvider) {
				connectParams.add(new BasicNameValuePair("email", myApp
						.getUserEmail()));
				connectParams.add(new BasicNameValuePair("roomname", myApp
						.getRoomName()));
				connectParams
						.add(new BasicNameValuePair("MAC", myApp.getMac()));
				connectParams.add(new BasicNameValuePair("ParamEnd",
						"ParamEndParamEndParamEnd"));
				return ConnectServer.connect(
						"http://" + ConnectServer.getServerAdd()
								+ "/game/provider-quit", connectParams);
			} else {
				connectParams.add(new BasicNameValuePair("userEmail", myApp
						.getUserEmail()));
				connectParams.add(new BasicNameValuePair("roomName", myApp
						.getRoomName()));
				connectParams
						.add(new BasicNameValuePair("mac", myApp.getMac()));
				connectParams.add(new BasicNameValuePair("ParamEnd",
						"ParamEndParamEndParamEnd"));
				return ConnectServer.connect(
						"http://" + ConnectServer.getServerAdd()
								+ "/game/quit-game", connectParams);
			}
		}

		@Override
		protected void onPostExecute(String result) {
			DialogTool.cancelProgressDialog(progressDialog);
			if (!DialogTool.checkNetworkAlive(result,
					ChallengerplayingActivity.this, null))
				return;
			if(!DialogTool.checkLogin(result, ChallengerplayingActivity.this))
				return;

			String[] resultParam = result.split(",");

			if ("OK".equals(resultParam[0])) {
				MiscTool.setMyAppQuitRoom(ChallengerplayingActivity.this);
				//startActivity(new Intent(ChallengerplayingActivity.this,
					//	RoomlistActivity.class));
				ChallengerplayingActivity.this.finish();
			} else {
				DialogTool.showCustomMessage(ChallengerplayingActivity.this,
						result);
			}
		}
	}

	private Runnable updateGameTask = new Runnable() {

		@Override
		public void run() {
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			connectParams.add(new BasicNameValuePair("email", myApp
					.getUserEmail()));
			connectParams.add(new BasicNameValuePair("roomname", myApp
					.getRoomName()));
			connectParams.add(new BasicNameValuePair("MAC", myApp.getMac()));
			connectParams.add(new BasicNameValuePair("ParamEnd",
					"ParamEndParamEndParamEnd"));
			String result = ConnectServer.connect(
					"http://" + ConnectServer.getServerAdd()
							+ "/challenger/update-game", connectParams);
			if (!DialogTool.checkNetworkAlive(result,
					ChallengerplayingActivity.this,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							mHandler.postDelayed(updateGameTask, 2000);

						}
					}))
				return;
			if(!DialogTool.checkLogin(result, ChallengerplayingActivity.this))
				return;
			result = result.replaceAll(" ", "");
			String[] resultParam = result.split(",");
			if ("OK".equals(resultParam[0])) {
				if ("finished".equals(resultParam[1])) {
					countDown.cancel();
					mHandler.removeCallbacks(updateGameTask);
					Intent intent = new Intent(ChallengerplayingActivity.this,
							GameoverActivity.class);
					intent.putExtra("word", resultParam[2]);
					SoundPlayer.playSound(R.raw.winner);
					startActivity(intent);
					ChallengerplayingActivity.this.finish();
				} else if ("reset".equals(resultParam[1])) {
					countDown.cancel();
					mHandler.removeCallbacks(updateGameTask);
					MiscTool.goToRoom(ChallengerplayingActivity.this,
							myApp.getUserEmail());
					ChallengerplayingActivity.this.finish();
				} else if ("fail".equals(resultParam[1])) {
					countDown.cancel();
					mHandler.removeCallbacks(updateGameTask);
					Intent intent = new Intent(ChallengerplayingActivity.this,
							GameoverActivity.class);
					intent.putExtra("word", resultParam[2]);
					SoundPlayer.playSound(R.raw.fail);
					startActivity(intent);
					ChallengerplayingActivity.this.finish();

				} else { // still in game, update view
					updateWord(resultParam[1]);
					updateKeyHangman(resultParam[1], resultParam[2]);
					setQuestionImage(resultParam[3]);
					/*----- Update challenger -----*/
					int nChallenger = (resultParam.length - 8) / 4;
					Player challenger[] = new Player[nChallenger];
					/*
					 * OK,A**LE,BKC,5.jpg,ken@mail.com vick@mail.com,vick,3.jpg,
					 * ken@mail.com,ken,5.jpg,100 gen@mail.com,genhana,6.jpg,95,
					 * dan@mail.com,dan,11.jpg,40
					 * milk@gmail.com,miruku,12.jpg,55
					 */

					for (int i = 0; i < nChallenger; i++) {
						challenger[i] = new Player();
						challenger[i].email = resultParam[8 + i * 4];
						challenger[i].name = resultParam[8 + i * 4 + 1];
						challenger[i].score = Integer
								.parseInt(resultParam[8 + i * 4 + 3]);
						challenger[i].imageURL = (resultParam[8 + i * 4 + 2]);
						if (resultParam[4].equals(challenger[i].email)) {
							challenger[i].isHisTurn = true;
						}
					}
					updateChallenger(challenger);
					/*----- Update provider -----*/
					Player provider = new Player();
					provider.email = resultParam[5];
					provider.name = resultParam[6];
					provider.imageURL = resultParam[7];
					setProvider(provider);

					if (resultParam[4].equals(myApp.getUserEmail())) {
						startMyTurn();
					}

					mHandler.postDelayed(this, 2000);
				}
			} else if ("ERROR".equals(resultParam[0])) {
				DialogTool.showCustomMessage(ChallengerplayingActivity.this,
						result);
			}
		}

	};
}
